package com.heliang.util;

import java.io.File;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.widget.ImageView;

import com.heliang.common.FileIOUtil;
import com.heliang.common.ImageDispose;
import com.heliang.common.ImageUtil;
import com.heliang.util.AsyncImageLoaderAddLoading.ImageCallback;
import com.hl.component.LoadingView;

public class ImageLoaderAddLoadingUtil {
	
	public static ImageLoaderAddLoadingUtil instance = new ImageLoaderAddLoadingUtil();
	private AsyncImageLoaderAddLoading asyncImageLoader;
	

	public ImageLoaderAddLoadingUtil() {
		// TODO Auto-generated constructor stub
		asyncImageLoader = new AsyncImageLoaderAddLoading();
	}
	
	/**
     * 图片回调（剪裁版本）
     */
    private AsyncImageLoaderAddLoading.ImageCallback imageCallback = new ImageCallback() {
    	@Override
        public void imageLoaded(String savePath,Drawable imageDrawable, List<LoadingView> livList) {

    		if (livList == null) {
				return;
			}
            
    		for (int i = 0; i < livList.size(); i++) {
    		    LoadingView liv = (LoadingView)livList.get(i);
    			if (liv == null || liv.getChildCount() <= 0) {
					continue;
				}
	    		ImageView iv = (ImageView)liv.getChildAt(0);
	    		if (iv != null && imageDrawable != null ) { // 防止图片url获取不到图片是，占位图片不见了的情况
	            	try {
	            		Bitmap bitmapDes;
	            		BitmapDrawable bd = (BitmapDrawable) imageDrawable;
	            		Bitmap bitmap = bd.getBitmap();
	                	float scale = calculateScale(bitmap.getWidth(), bitmap.getHeight(),
	            				iv.getDrawable().getIntrinsicWidth(),iv.getDrawable().getIntrinsicHeight());
	            		
	                	if (bitmap.getWidth() == iv.getDrawable().getIntrinsicWidth() && bitmap.getHeight() == iv.getDrawable().getIntrinsicHeight()) {
	                		bitmapDes = bitmap;
						}else {
							bitmapDes = ImageUtil.zoomImage(bitmap, scale);
		            		int x = (bitmapDes.getWidth() - iv.getDrawable().getIntrinsicWidth())/2;
		            		int y = (bitmapDes.getHeight() - iv.getDrawable().getIntrinsicHeight())/2;
		            		
		            		bitmapDes = Bitmap.createBitmap(bitmapDes, x, y, iv.getDrawable().getIntrinsicWidth(), iv.getDrawable().getIntrinsicHeight());
						}
	                	
	                	File fileTmp = new File(savePath);
	                	if (!fileTmp.exists()) {
	                		FileIOUtil.saveImage(ImageDispose.Bitmap2Bytes(bitmapDes), savePath);//保存已经裁剪的图片
						}
	            		
	            		
	            		iv.setImageBitmap(bitmapDes);
	            		if (liv.getChildAt(1) != null) {
	            			liv.removeViewAt(1);//remove loading
						}
	            		
//	            		imageDrawable = null;
//	            		liv.removeViewAt(1);//remove loading
	//            		iv.setImageDrawable(imageDrawable);
					} catch (Exception e) {
						// TODO: handle exception
						Log.e(Constants.TAG, e.getMessage());
					}
	            	
	            }
    		}
        }
    };  
    
    /**
     * 图片回调（保存不裁剪版本）
     */
    private AsyncImageLoaderAddLoading.ImageCallback imageCallbackSaveNoCut = new ImageCallback() {
    	@Override
        public void imageLoaded(String savePath,Drawable imageDrawable, List<LoadingView> livList) {
//            ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
//            Log.i("test", "Drawable cachedImage = asyncImageLoader.loadDrawable( )-->");
    		
    		if(livList == null || livList.size() <= 0){
    			return;
    		}
    		
    		for (int i = 0; i < livList.size(); i++) {
    		    LoadingView liv = (LoadingView)livList.get(i);
    			
    			if (liv == null || liv.getChildCount() <= 0) {
                	return;
    			}
                
        		ImageView iv = (ImageView)liv.getChildAt(0);
        		if (iv != null && imageDrawable != null ) { // 防止图片url获取不到图片是，占位图片不见了的情况
                	try {
                		Bitmap bitmapDes;
                		BitmapDrawable bd = (BitmapDrawable) imageDrawable;
                		Bitmap bitmap = bd.getBitmap();
                    	float scale = calculateScale(bitmap.getWidth(), bitmap.getHeight(),
                				iv.getDrawable().getIntrinsicWidth(),iv.getDrawable().getIntrinsicHeight());
                		
                    	
                    	File fileTmp = new File(savePath);
                    	if (!fileTmp.exists()) {
                    		FileIOUtil.saveImage(ImageDispose.Bitmap2Bytes(bitmap), savePath);//保存已经裁剪的图片
    					}
                    	
                    	if (bitmap.getWidth() == iv.getDrawable().getIntrinsicWidth() && bitmap.getHeight() == iv.getDrawable().getIntrinsicHeight()) {
                    		bitmapDes = bitmap;
    					}else {
    						bitmapDes = ImageUtil.zoomImage(bitmap, scale);
    	            		int x = (bitmapDes.getWidth() - iv.getDrawable().getIntrinsicWidth())/2;
    	            		int y = (bitmapDes.getHeight() - iv.getDrawable().getIntrinsicHeight())/2;
    	            		
    	            		bitmapDes = Bitmap.createBitmap(bitmapDes, x, y, iv.getDrawable().getIntrinsicWidth(), iv.getDrawable().getIntrinsicHeight());
    					}
                    	
                    	
                		
                		
                		iv.setImageBitmap(bitmapDes);
                		liv.removeViewAt(1);//remove loading
                		
                		imageDrawable = null;
//                		iv.setImageDrawable(imageDrawable);
    				} catch (Exception e) {
    					// TODO: handle exception
    					Log.e(Constants.TAG, e.getMessage());
    				}
                	
                }
			}
    		
        }
    };
    
    
    /**
     * 图片回调,根据宽高直接拉伸图片
     */
    private AsyncImageLoaderAddLoading.ImageCallback imageCallbackZoom = new ImageCallback() {
    	@Override
        public void imageLoaded(String savePath,Drawable imageDrawable, List<LoadingView> livList) {
//            ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
//            Log.i("test", "Drawable cachedImage = asyncImageLoader.loadDrawable( )-->");
    		
    		if(livList == null || livList.size() <= 0){
    			return;
    		}
    		
    		for (int i = 0; i < livList.size(); i++) {
    		    LoadingView liv = (LoadingView)livList.get(i);
    			
    			if (liv == null || liv.getChildCount() <= 0) {
                	return;
    			}
                
        		ImageView iv = (ImageView)liv.getChildAt(0);
        		if (iv != null && imageDrawable != null ) { // 防止图片url获取不到图片是，占位图片不见了的情况
                	try {
                		Bitmap bitmapDes;
                		BitmapDrawable bd = (BitmapDrawable) imageDrawable;
                		Bitmap bitmap = bd.getBitmap();
//                    	float scale = calculateScaleNoCut(bitmap.getWidth(), bitmap.getHeight(),
//                				iv.getDrawable().getIntrinsicWidth(),iv.getDrawable().getIntrinsicHeight());
                		
                    	
                    	File fileTmp = new File(savePath);
                    	if (!fileTmp.exists()) {
                    		FileIOUtil.saveImage(ImageDispose.Bitmap2Bytes(bitmap), savePath);//保存已经裁剪的图片
    					}
                    	
                    	if (bitmap.getWidth() == iv.getDrawable().getIntrinsicWidth() && bitmap.getHeight() == iv.getDrawable().getIntrinsicHeight()) {
                    		bitmapDes = bitmap;
    					}else {
    						bitmapDes = ImageDispose.zoomBitmap(bitmap, iv.getDrawable().getIntrinsicWidth(), iv.getDrawable().getIntrinsicHeight());
//    	            		int x = (bitmapDes.getWidth() - iv.getDrawable().getIntrinsicWidth())/2;
//    	            		int y = (bitmapDes.getHeight() - iv.getDrawable().getIntrinsicHeight())/2;
//    	            		
//    	            		bitmapDes = Bitmap.createBitmap(bitmapDes, x, y, iv.getDrawable().getIntrinsicWidth(), iv.getDrawable().getIntrinsicHeight());
    					}
                    	
                    	
                		
                		
                		iv.setImageBitmap(bitmapDes);
                		liv.removeViewAt(1);//remove loading
                		
                		
//                		iv.setImageDrawable(imageDrawable);
    				} catch (Exception e) {
    					// TODO: handle exception
    					Log.e(Constants.TAG, e.getMessage());
    				}
                	
                }
			}
    		
        }
    };
    
    
    /**
     * 图片回调（剪裁版本,修改背景）iv.setBackgroundDrawable(imageDrawable);
     */
    private AsyncImageLoaderAddLoading.ImageCallback imageCallbackSetBackground = new ImageCallback() {
    	@Override
        public void imageLoaded(String savePath,Drawable imageDrawable, List<LoadingView> livList) {

    		if (livList == null) {
				return;
			}
            
    		for (int i = 0; i < livList.size(); i++) {
    		    LoadingView liv = (LoadingView)livList.get(i);
    			if (liv == null || liv.getChildCount() <= 0) {
					continue;
				}
	    		ImageView iv = (ImageView)liv.getChildAt(0);
	    		if (iv != null && imageDrawable != null ) { // 防止图片url获取不到图片是，占位图片不见了的情况
	            	try {
	            		Bitmap bitmapDes;
	            		BitmapDrawable bd = (BitmapDrawable) imageDrawable;
	            		Bitmap bitmap = bd.getBitmap();
	                	float scale = calculateScale(bitmap.getWidth(), bitmap.getHeight(),
	            				iv.getBackground().getIntrinsicWidth(),iv.getBackground().getIntrinsicHeight());
	            		
	                	if (bitmap.getWidth() == iv.getDrawable().getIntrinsicWidth() && bitmap.getHeight() == iv.getDrawable().getIntrinsicHeight()) {
	                		bitmapDes = bitmap;
						}else {
							bitmapDes = ImageUtil.zoomImage(bitmap, scale);
		            		int x = (bitmapDes.getWidth() - iv.getBackground().getIntrinsicWidth())/2;
		            		int y = (bitmapDes.getHeight() - iv.getBackground().getIntrinsicHeight())/2;
		            		
		            		bitmapDes = Bitmap.createBitmap(bitmapDes, x, y, iv.getBackground().getIntrinsicWidth(), iv.getBackground().getIntrinsicHeight());
						}
	                	
	                	File fileTmp = new File(savePath);
	                	if (!fileTmp.exists()) {
	                		FileIOUtil.saveImage(ImageDispose.Bitmap2Bytes(bitmapDes), savePath);//保存已经裁剪的图片
						}
	            		
//	                	imageDrawable.setBounds(0, 0, 540, 195);
	            		iv.setBackgroundDrawable(imageDrawable);
	            		
	            		if (liv.getChildAt(1) != null) {
	            			liv.removeViewAt(1);//remove loading
						}
	            		
//	            		liv.removeViewAt(1);//remove loading
	//            		iv.setImageDrawable(imageDrawable);
					} catch (Exception e) {
						// TODO: handle exception
						Log.e(Constants.TAG, e.getMessage());
					}
	            	
	            }
    		}
        }
    };  
    
    
    /**
     * 设置需要异步加载的图片
     */
    public LoadingView setImageDrawable(String imagePath,String imageUrl,LoadingView liv){
    	return asyncImageLoader.loadDrawable(imagePath, imageUrl,liv, imageCallback);
    }
    
    
    /**
     * 设置需要异步加载的图片,保存不裁减缩放的原图
     */
    public LoadingView setImageDrawableSaveNoCut(String imagePath,String imageUrl,LoadingView liv){
    	return asyncImageLoader.loadDrawable(imagePath, imageUrl,liv, imageCallbackSaveNoCut);
    	
    }
    
    /**
     * 设置需要异步加载的图片,缩放
     */
    public LoadingView setImageDrawableZoom(String imagePath,String imageUrl,LoadingView liv){
    	return asyncImageLoader.loadDrawable(imagePath, imageUrl,liv, imageCallbackZoom);
    	
    }
    
    /**
     * 设置需要异步加载的图片
     */
    public LoadingView setImageBackground(String imagePath,String imageUrl,LoadingView liv){
    	return asyncImageLoader.loadDrawable(imagePath, imageUrl,liv, imageCallbackSetBackground);
    }
    
    /**
     * 设置需要异步加载的图片，自己传回调
     */
    public LoadingView setImageDrawableNoCut(String imagePath,String imageUrl,LoadingView lv,ImageCallback imageCallbackNoCut,boolean checkContain){
    	return asyncImageLoader.loadDrawable(imagePath, imageUrl,lv, imageCallbackNoCut);
    	
    }
    
    /**
	 * 算出需要缩放的比例(裁剪)
	 * @param width
	 * @param height
	 * @return
	 */
	public static float calculateScale(int widthOrg,int heightOrg,int widthDes,int heightDes){
		float widthScale = (float)widthDes/widthOrg;
		float heightScale = (float)heightDes/heightOrg;
		return widthScale < heightScale?heightScale:widthScale;
	}
	
	/**
	 * 算出需要缩放的比例(裁剪)
	 * @param width
	 * @param height
	 * @return
	 */
	public static float calculateScaleNoCut(int widthOrg,int heightOrg,int widthDes,int heightDes){
		float widthScale = (float)widthDes/widthOrg;
		float heightScale = (float)heightDes/heightOrg;
		return widthScale > heightScale?heightScale:widthScale;
	}

}
